package com.wyh.springcloud.controller;


import com.wyh.springcloud.service.impl.PaymentServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;
import pojo.CommonResult;
import pojo.Payment;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author wyh
 * @version 1.0
 * @date 2021/11/2 16:37
 */
@RestController
@Slf4j
public class PaymentController {

    @Autowired
    private PaymentServiceImpl paymentService;

    @Resource
    private DiscoveryClient discoveryClient;

    @Value("${server.port}")
    private String ServerPort;

    @PostMapping(value = "/payment/add")
    public CommonResult addPayment(@RequestBody Payment payment){
        int result = paymentService.addPayment(payment);
        log.info(ServerPort+"*******添加用户成功");
        if (result > 0){
            return new CommonResult(200,"success",result);
        }
        return new CommonResult(500,"error",null);
    }

    @GetMapping(value = "/payment/findAll")
    public CommonResult findAll(){
        List<Payment> payments = paymentService.findAll();
        log.info(ServerPort+"*******查用户成功"+payments);
        if (payments.size() > 0){
            return new CommonResult(200,"success",payments);
        }
        return new CommonResult(500,"error",null);
    }

    @GetMapping(value = "/payment/getPaymentById/{id}")
    public CommonResult getPaymentById(@PathVariable("id") Long id){
        Payment payment = paymentService.getPaymentById(id);
        log.info(ServerPort+"*******id查用户成功"+payment);
        if (payment != null){
            return new CommonResult(200,"success",payment);
        }
        return new CommonResult(500,"error",null);
    }

    @GetMapping("/payment/discovery")
    public Object discovery(){
        List<String> services = discoveryClient.getServices();
        for (String element : services) {
            log.info("******element: "+element);
        }

        List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
        for (ServiceInstance instance : instances) {
            log.info(instance.getServiceId()+"\t"+instance.getHost()+"\t"+instance.getPort()+"\t"+instance.getUri());
        }
        return discoveryClient;
    }

    @GetMapping(value = "/payment/lb")
    public String lbPort(){
        return ServerPort;
    }

    @GetMapping(value = "/payment/timeout")
    public String timeout(){
        try {
            TimeUnit.SECONDS.sleep(1);
        }catch (Exception e){
            e.printStackTrace();
        }
        return ServerPort;
    }
}
